package com.ecspace.knowledgegraphapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecspace.knowledgegraphapi.domain.dto.NodeDTO;
import com.ecspace.knowledgegraphapi.domain.dto.NodeRelationDTO;
import com.ecspace.knowledgegraphapi.domain.dto.PropDTO;
import com.ecspace.knowledgegraphapi.domain.entity.Node;
import com.ecspace.knowledgegraphapi.domain.entity.Relation;
import com.ecspace.knowledgegraphapi.mapper.NodeMapper;
import com.ecspace.knowledgegraphapi.service.INodeService;
import com.ecspace.knowledgegraphapi.service.IRelationService;
import com.ecspace.knowledgegraphapi.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class NodeServiceImpl extends ServiceImpl<NodeMapper, Node> implements INodeService {

    @Autowired
    private IRelationService relationService;

    @Override
    public String saveOneNode(NodeDTO node) {

        String id = StrUtil.getUUIDStr();

        String name = node.getName();
        String label = node.getLabel();

        List<PropDTO> propList = node.getProps();
        String attrListStr = JSON.toJSONString(propList);
        Node tnode = new Node();
        tnode.setId(id);
        tnode.setName(name);
        tnode.setLabel(label);
        tnode.setProps(attrListStr);

        boolean saveOk = save(tnode);
        if (saveOk) {
            return id;
        } else {
            return "";
        }
    }

    @Override
    public List<NodeDTO> findNodesByFromNodeId(String fromNodeId) {

        LambdaQueryWrapper<Relation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Relation::getFromId, fromNodeId);
        List<Relation> relationList = relationService.list(wrapper);

        if (!relationList.isEmpty()) {
            List<String> ids = relationList.stream().map(Relation::getToId).collect(Collectors.toList());
            List<Node> nodes = listByIds(ids);
            List<NodeDTO> nodeDTOList = nodes.stream()
                    .map(item -> new NodeDTO(item.getId(), item.getName(), item.getLabel(), item.getProps()))
                    .collect(Collectors.toList());
            return nodeDTOList;
        }

        return new ArrayList<>();
    }


}
